package com.g4.shoppingsingle.util;

import com.g4.shoppingsingle.pojo.DdProductInfo;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;

@Component
public class HttpParseUtil {

//    public static void main(String[] args) throws IOException, InterruptedException {
//        List<Content> mi = new HttpParseUtil().parseJD("mi");
//        mi.forEach(System.out::println);
//    }

    public  List<DdProductInfo> parseMi(String keywords) throws IOException, InterruptedException {
        //获取请求 https://search.jd.com/Search?keyword=java
        String url = "https://search.jd.com/Search?keyword="+keywords;
        //解析网页
        Document document = Jsoup.parse(new URL(url),30000);
        Element element = document.getElementById("J_goodsList");
//        System.out.println(element.html());
        //获取li
        Elements li = element.getElementsByTag("li");
        List<DdProductInfo> goodsList = new ArrayList<>();

        //获取元素中的内容
        for (Element el : li) {
            String img = el.getElementsByTag("img").eq(0).attr("data-lazy-img");
//            String imgs = el.getElementsByTag("img").eq(0).attr("source-data-lazy-img");
//            String src = el.getElementsByTag("img").eq(0).attr("src");
            String price = el.getElementsByClass("p-price").eq(0).text();
            String advantage = el.getElementsByClass("p-name").eq(0).text();
            DdProductInfo ddProductInfo = new DdProductInfo();
            ddProductInfo.setAdvantage(advantage)
                        .setPdImage(img)
                        .setPromotion(price);
            goodsList.add(ddProductInfo);
        }
        return goodsList;
    }
}
